package com.zwcloud.zw.railway.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zwcloud.zw.railway.entity.Destination;
import com.zwcloud.zw.railway.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取运往地
 * */
@Service
public class DestinationService {

    @Autowired
    private HttpUtils httpUtils;

    private static final String DESTINATION_LIST_URL = "http://120.71.225.100:8866/railway/dest/queryDivisionListForYardId";
    private static final String ACCESS_CODE = "sRrWpAF3Da42GuQVuzgICA==";


    public List<Destination> getDestinationList() throws Exception {
        // 拼接 URL 和查询参数
        String urlWithParams = DESTINATION_LIST_URL + "?accessCode=" + ACCESS_CODE;
        ResponseEntity<String> response = httpUtils.sendGetRequest(urlWithParams);

        System.out.println("原始响应内容: " + response.getBody()); // 调试用
        if (response.getStatusCode().is2xxSuccessful()) {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(response.getBody());
            JsonNode dataNode = root.path("data");
            List<Destination> destinations = new ArrayList<>();
            if (dataNode.isArray()) {
                for (JsonNode node : dataNode) {
                    Destination destination = new Destination();
                    destination.setId(node.path("id").asText());
                    destination.setRailwayPlatformName(node.path("railwayPlatformName").asText());
                    destinations.add(destination);
                }
            } else {
                System.out.println("data 字段不是数组或不存在");
            }
            return destinations;
        } else {
            throw new Exception("获取目的地列表失败，状态码: " + response.getStatusCode());
        }
    }
}